import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import './category.scss';
import DataForm from './form';
import { Layout, Tree,Button,Form,Table,Input, Popconfirm,Spin,InputNumber,Modal,Pagination, message} from 'antd';
import { getAllCategoryInfos, getTreeData, getNumber, insertNewCategory, deleteCategory, updateCatalogue} from '../../../api/resourceCategory/resourceCategory'
import { login} from '../../../api/resourceService/applicationApi'
import Folder from './folder1.png';
const { Content,Sider,Header } = Layout;
const titleStyle={
  color:'rgb(0,126,220)',height:54.6,width:520,backgroundColor:'#f0f3f6',position:'absolute',left:0,top:0,display:'flex',
  alignItems:'center',paddingLeft:24,fontWeight:'bold',borderBottom:'2px solid #e5e6e8',zIndex:2
} 
const footerStyle={
  backgroundColor:'#e6eef5',width:520,height:53,position:'absolute',left:0,bottom:0,
  display:'flex',alignItems:'center',justifyContent:'center'
}
const valutToType = {
  1: '类', 2: '项', 3: '目', 4: '细目' //根据树的层，获得当前的名字
}
//列表返回里4,3,2,1分别对应类，项,目，细目
const valueToType2 = {
  4: '类', 3: '目', 2: '项', 1: '类'
}
const valueToState = {
  1: '启用', 0: '未启用'
}
class Category extends Component{
  constructor() {
    super()
    this.columns=[
      {
        title:'序号',
        key:'index',
        dataIndex:'index',
      },
      {
        title:'编码',
        key:'number',
        dataIndex:'number',
      },
      {
        title:'分类',
        key:'type',
        dataIndex:'type',
        render:(text,record)=>{
          return <span>{valueToType2[text]}</span>
      }
      },
      {
        title:'名称',
        key:'name',
        dataIndex:'name',
      },
      {
        title:'状态',
        key:'isEnable',
        dataIndex:'isEnable',
        render:(text,record)=>{
        return <span >{valueToState[text]}</span>
        }
      },
      {
        title:'创建时间',
        key:'createTime',
        dataIndex:'createTime',
      },
      {
        title:'操作',
        key:'action',
        dataIndex:'action',
        render:(text,record)=>{
          return <div>
            <Button type='link' disabled={record.isEnable === 1} onClick={()=>this.editor(record)}>编辑</Button>
            <Popconfirm
                title="确认删除?"
                onConfirm={() => this.deleteRecord(record)}
                okText="确定"
                cancelText="取消"
              >
                <Button size="small" type="link"  disabled={record.isEnable === 1} style={{ marginLeft: 10 }}>
                  删除
                  </Button>
              </Popconfirm>
          </div>
        }
      },
    ]
    this.state={
      total:20,
      page:1,
      totalPage:2,
      type: '',//类别 4，3，2，1
      name:'',
      number:'',
      curLayer:'',//树的第几层
      treeData :[],
      initialData: {},
      addVisible:false,
      dataSource:[],
      editorVisible:false,
      paginationNo: {
        pageSize: 10,
        defaultCurrent:1,
        current:1,
      },
    }
  }

  changeName=(e)=>{
    this.setState({
      name:e.target.value
    });
  }
  onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
    let layer = info.node.layer
    let obj = {
      upType: valutToType[layer-1] ,//上级类型
      curType: valutToType[layer],
      name: '',
      type: info.node.type,
      departMent: info.node.title,
      curNumber: '',
      superNumber: info.node.key,
      description: '',
      layer: layer
    }
    this.setState({initialData: obj})
    getAllCategoryInfos({pageNum: 1, pageSize: 10,number:selectedKeys[0]}).then(res => {
      if(res.data.metaData.code === 'success') {
        const paginationNo = this.state.paginationNo
        paginationNo.total = res.data.data.total
        paginationNo.current = res.data.data.pageNum
        let index1 = 1
        res.data.data.list.forEach(element => {
          element['index'] = index1++
        });
        this.setState({dataSource: res.data.data.list})
      }
    })
  }

  changeNumber=(e)=>{
    this.setState({
      number:e.target.value
    })
  }
  searchForm=React.createRef();

  search=()=>{
    this.getCategoryInfo(1,10,this.state.initialData.superNumber)
    this.searchForm.current.validateFields().then(values=>{
      console.log(values);
    })
  }

  resetForm=()=>{
    console.log(this.searchForm,12);
    console.log(this.Form,123);
    console.log(this.DataForm,1234);
    console.log(this.DataForm,1234);
    //测试 获取登录人loken
    login({username:'test',password:'test'}).then(res=>{
      console.log(res)
    })
    this.searchForm.current.resetFields();
  }

  editor=(record)=>{
    console.log('edit', record)
    let initialData = this.state.initialData
    let obj = {
      upType: valueToType2[record.type+1] ,//上级类型
      curType: valueToType2[record.type],
      superNumber: record.superNumber,
      name: record.name,
      curNumber: record.number,
      description: record.description,
    }
    this.setState({
      editorVisible:true,
      initialData: obj,
      record
    })
  }
  changePage=(page)=>{
    this.setState({
      page
    })
  }

  deleteRecord=(record)=>{
    deleteCategory({number: record.number}).then( res => {
      if(res.data.metaData.code === 'success') {
        message.success('删除成功')
        this.initTreeData()
      }else{
        message.error(res.data.metaData.message)
      }
    })
  }

  handleAdd=()=>{
    const initialData = this.state.initialData
    console.log('initialData', initialData)
    if(initialData.type === 4) {
      message.info('当前选中项不可新增，')
    }
    else {
      let type = 5-parseInt(initialData.layer)
      let params = {
        superNumber: initialData.superNumber,
        type: type
      }
      getNumber(params).then(res => {
        if(res.data.metaData.code === 'success') {
          this.setState({initialData: {...initialData, curNumber: res.data.data}, addVisible: true, type:type})

        }
      })
    }
  }

  handleTableChange = (pagination) => {
    const pager = { ...this.state.paginationNo };
    pager.current = pagination.current;
    this.setState({
      paginationNo: pager,
    });
    this.getCategoryInfo(pagination.current, pagination.pageSize)
  }

  addCategory=()=>{
    this.addData.validateFields().then(values => {
      const { initialData, type}= this.state
      console.log(values);
      let params = {name: values.name,description: values.description, type: type, number:  initialData.curNumber, superNumber: initialData.superNumber}
      insertNewCategory(params).then(res => {
        if(res.data.metaData.code === 'success') {
          message.success('添加成功')
          this.initTreeData()
        }
      })
      this.setState({
        addVisible:false
      })
    }).catch(err=>{
    });
  }

  updateCategory = () => {
    this.addData.validateFields().then(values => {
      const { initialData, type}= this.state
      console.log(values);
      let params = {name: values.name,description: values.description, type: type, number:  initialData.curNumber,}
      updateCatalogue(params).then(res => {
        if(res.data.metaData.code === 'success') {
          message.success('修改成功')
          this.setState({editorVisible: false})
          this.getCategoryInfo(1,10)
          this.initTreeData()
        }
      })
      this.setState({
        addVisible:false
      })
    }).catch(err=>{
    });
  }

  

  editorCategory=()=>{
    this.setState({
      editorVisible:false
    })
  }

  handleCancel=()=>{
    this.setState({
      addVisible:false,
      editorVisible:false
    })
  }

  componentWillMount() {
    this.initTreeData(true)
  }
  initTreeData(isFirst){
    if(isFirst){
      getTreeData({notDetail:1}).then(res => {
        console.log(res.data)
        const arr = res.data.data;
        this.getCategoryInfo(1,10,arr.length && arr[0].children[0]? arr[0].children[0].key:arr[0].key)
        let layer = arr.length && arr[0].children[0]? 2:1
        let curData = arr.length && arr[0].children[0]? arr[0].children[0]:arr[0]
        let obj = {
          upType: valutToType[layer-1] ,//上级类型
          curType: valutToType[layer],
          name: '',
          type: curData.type,
          departMent: curData.title,
          curNumber: '',
          superNumber: curData.key,
          description: '',
          layer: layer
        }
        this.setState({initialData: obj})
        let c = this.formatTreeData(res.data.data,1)
        this.setState({treeData:c})
      })
    }else{
      getTreeData({notDetail:1}).then(res => {
        console.log(res.data)
        this.getCategoryInfo(1,10,this.state.initialData.superNumber)
        let c = this.formatTreeData(res.data.data,1)
        this.setState({treeData:c})
      })
    }
  }

  getCategoryInfo = (page, pageSize,key) => {
    // this.onSelect()
   
    getAllCategoryInfos({pageNum: page, pageSize: pageSize,number:key}).then(res => {
      if(res.data.metaData.code === 'success') {
        const paginationNo = this.state.paginationNo
        paginationNo.total = res.data.data.total
        paginationNo.current = res.data.data.pageNum
        let index1 = 1
        res.data.data.list.forEach(element => {
          element['index'] = index1++
        });
        this.setState({dataSource: res.data.data.list})
        
      }
    })
  }

  formatTreeData = (data, layer) => {
    data.map((item, index) => {
      if(item.children&& (JSON.stringify(item.children) !== '[]') && item.children.length > 0) {
        item.layer = layer
        item.icon = <img src={Folder} alt='未知' />
        this.formatTreeData(item.children, layer+1)
        // item.layer = curLayer
        // curLayer = layer+1
        // console.log('cur item', item, layer, index)
        // this.formatTreeData(item.children, curLayer)
      }
      else {
        item.layer = layer
      }
    })
    return data
  }

  render(){
    const {total,page,totalPage,name,number,addVisible,editorVisible, treeData, dataSource}=this.state;
    return (
      <Content style={{position:"relative",left:-24}} className='out-content' >
        <Layout className='layout'>
          <Sider className='sider'>
          { treeData.length > 0 && 
            <Tree
              showLine={true}
              showIcon={true}
              treeData={treeData}
              defaultExpandAll={true}
              defaultSelectedKeys={ treeData[0]  && treeData[0].children[0]?[treeData[0].children[0].key]:[treeData[0].key] }
              onSelect={this.onSelect}
            />
          }
            
          </Sider>
          <Layout className='rightLayout'>
            <Header className='right-header'>
              <p className='title'>目录分类</p>
              <Button type='primary' style={{position:'absolute',right:0}} onClick={this.handleAdd}>新增</Button>
            </Header>
            <Content className='content'>
              <div className='form-inline'>
                <Form layout='inline' ref={this.searchForm}>
                  <Form.Item label='目录分页名称' colon={false} name='name'>
                    <Input />
                  </Form.Item>
                  <Form.Item label='编码' colon={false} name='number'>
                    <Input />
                  </Form.Item>
                  <Form.Item>
                    <Button type='primary' onClick={this.search} >查询</Button>
                  </Form.Item>
                  <Form.Item>
                    <Button type='primary' onClick={this.resetForm}>重置</Button>
                  </Form.Item>
                </Form>
              </div>
              <div className='table-box'>
                <Spin spinning={false}>
                  <Table
                    columns={this.columns} size='small' bordered
                    dataSource={dataSource}
                    rowKey={record => record.id}
                    className='table'
                    onChange={this.handleTableChange}
                    pagination={this.state.paginationNo}
                  />
                  {/* <Pagination current={page} pageSize={10} total={total} onChange={this.changePage} style={{position:'absolute',bottom:20,right:10}}/>
                  <div className='footer'>
                    显示<InputNumber min={1} max={totalPage} defaultValue={page} />项结果，共{total}项
                  </div> */}
                </Spin>
              </div>
            </Content>
          </Layout>
        </Layout>
        <Modal
          title={<div style={titleStyle}>新增目录分类</div>}
          onCancel={this.handleCancel}
          visible={addVisible}
          bodyStyle={{backgroundColor:'#f0f3f6'}}
          footer={<div style={footerStyle}>
            <Button type='primary' style={{color:'white',borderRadius:5}} onClick={this.addCategory}>保存</Button>
            <Button style={{color:'#007cdb',borderRadius:5}} onClick={this.handleCancel}>取消</Button>
          </div>}
        >
          {addVisible && <DataForm onRef={ref=>this.addData=ref} departMentShow={true} initialData={this.state.initialData} /> }
        </Modal>
        <Modal
          title='编辑目录分类'
          onOk={this.editorCategory}
          onCancel={this.handleCancel}
          visible={editorVisible}
          footer={<div style={footerStyle}>
            <Button type='primary' style={{color:'white',borderRadius:5}} onClick={this.updateCategory}>保存</Button>
            <Button style={{color:'#007cdb',borderRadius:5}} onClick={this.handleCancel}>取消</Button>
          </div>}
        >
          {editorVisible && <DataForm onRef={ref => this.addData=ref} departMentShow={false} initialData={this.state.initialData} />}
        </Modal>
      </Content>
    );
  }
}

const mapStateToProps = (state) => {
  return {
  }
}

const mapDispatchToProps = (dispatch) => ({
})

export default connect(mapStateToProps, mapDispatchToProps)(Category);